package com.nilhcem.fakesmtp.eventbus;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class SaveFileSubscribe {

    private static final Logger LOGGER = LoggerFactory.getLogger(SaveFileSubscribe.class);

    @Subscribe
    @AllowConcurrentEvents
    public void subscribe(SaveFileEvent event) {
        File file = new File(event.getFileName());
        try {
            if (!file.exists()) {
                FileUtils.writeStringToFile(file, event.getContent());
            } else {
                throw new IOException("File already exists: " + file.getAbsolutePath());
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
